package com.github.rxyor.netty.exemple.case4;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import java.time.LocalDateTime;

/**
 *<p>
 *
 *</p>
 *
 * @author liuyang
 * @date 2020/5/24 周日 11:34:00
 * @since 1.0.0
 */
public class TextWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg)
        throws Exception {
        System.out.println(String.format("Server Received:[%s]", msg.text()));
        ctx.channel().writeAndFlush(String.format("Server Response:[%s]", LocalDateTime.now()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println(
            String.format("handlerAdded, channel id:[%s]", ctx.channel().id().asLongText()));
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println(
            String.format("handlerRemoved, channel id:[%s]", ctx.channel().id().asLongText()));
    }
}
